package com.hqyj.javaGraduation.account.service.Impl;

import com.hqyj.javaGraduation.account.dao.UserDao;
import com.hqyj.javaGraduation.account.pojo.User;
import com.hqyj.javaGraduation.account.service.UserService;
import com.hqyj.javaGraduation.utils.MyEmail;
import com.hqyj.javaGraduation.utils.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;

@Service
public class UserServiceImpl implements UserService{

    @Autowired
    private UserDao userDao;
    @Autowired(required = false)
    private MyEmail email;
    @Autowired
    private RedisTemplate<String,Object> redisTemplate;
    @Autowired
    private RedisUtils redisUtils;

    @Override
    public User userLogin(User user) {
        return userDao.userLogin(user);
    }

    @Override
    public int registerUser(User user) {
        return userDao.Register(user);
    }

    @Override
    public HashMap<String, Object> emailSend(String mail, HttpServletRequest req) {
        HashMap<String, Object> map = new HashMap();
        //生成4位随机石
        Random rd = new Random( ) ;
        int code = rd.nextInt(10000) ;
        map = email.sendMail(mail, "你的验证码是: "+code);
        if(map.get("info").equals("发送成功")){
            HttpSession session = req.getSession();
            session.setAttribute("code",code);
        }
        return map;
    }

    @Override
    public HashMap<String, Object> emailRedis(String mail) {
        HashMap<String, Object> map = new HashMap<String, Object>();
        //生成4位随机
        Random rd = new Random();
        int code = rd.nextInt(10000);
        map = email.sendMail(mail,"你的验证码是："+code);
        if(map.get("info").equals("发送成功")){
            //存入redis
            redisTemplate.opsForValue().set(mail,code+"",3, TimeUnit.MINUTES);
        }
        return map;
    }

    @Override
    public HashMap<String, Object> LoginEmailRedis(String code,String email) {
        HashMap<String,Object> map = new HashMap<String,Object>();
        String code1 = redisTemplate.opsForValue().get(email)+"";
        if(code.equals(code1)){
            map.put("info","邮箱登录成功");
        }else{
            map.put("info","验证码输入不正确");
        }
        return map;
    }

    @Override
    public HashMap<String, Object> updatePwd(User user) {
        HashMap<String,Object> map = new HashMap<>();
        int num = userDao.updatePwd(user);
        if (num != 0){
            map.put("info","修改成功");
        }else{
            map.put("info","修改失败");
        }
        return map;
    }
}
